/*
 * Copyright (c) 2017,安徽皖通科技股份有限公司 All rights reserved.
 */

package com.wttech.dzzf.process.service.upload.blacklist;

import cn.com.taiji.common.manager.net.http.binclient.ApiRequestException;
import cn.com.taiji.sdk.comm.ETCCommHelper;
import cn.com.taiji.sdk.model.comm.protocol.AbstractSdtsRequest;
import cn.com.taiji.sdk.model.comm.protocol.AbstractSdtsResponse;
import cn.com.taiji.sdk.model.comm.protocol.backlist.CardBlackListUploadRequest;
import cn.com.taiji.sdk.model.comm.protocol.backlist.CardBlackListUploadResponse;
import cn.com.taiji.sdk.model.comm.protocol.backlist.OBUBlackListUploadRequest;
import cn.com.taiji.sdk.model.comm.protocol.backlist.OBUBlackListUploadResponse;
import cn.com.taiji.sdk.tools.JsonTools;
import com.wtkj.vo.dzzf.base.kfwd.CardInfo;
import com.wtkj.vo.dzzf.base.kfzx.ListRealRecord;
import com.wtkj.vo.dzzf.share.staticvalue.CardStaticValue;
import com.wttech.dzzf.process.constant.ExecuteTable;
import com.wttech.dzzf.process.dao.BlackListInfoDao;
import com.wttech.dzzf.process.dao.TransferUserInfoDao;
import com.wttech.dzzf.process.model.UploadRsp;
import com.wttech.dzzf.process.model.user.Obu;
import com.wttech.dzzf.process.service.base.BaseInfoService;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Future;

import static com.wttech.dzzf.process.constant.UserConstants.DEFAULT_PROCESS_NUM;

/**
 * 黑名单信息上传服务
 *
 * @author MaShibo
 * @date 2017/12/25.
 */
@Service
public class BlackListUploadService {

	private static final Logger LOGGER = LoggerFactory.getLogger(BlackListUploadService.class);

	private static final String DEFAULT_ISSUERNO = "610107";

	private static final int DEFAULT_OLD_CARD_BLTYPE = 4;

	@Resource
	private BlackListInfoDao blackListInfoDao;

	@Resource
	private TransferUserInfoDao transferUserInfoDao;

	@Resource
	private ThreadPoolTaskExecutor executor;

	@Resource
	private BaseInfoService baseInfoService;

	private boolean isRunning = false;

	@Scheduled(fixedDelay = 1000 * 30)
	public void monitor() {
		if (!isRunning) {
			return;
		}
		int success = blackListInfoDao.queryBlListUploadNum(1);
		int failure = blackListInfoDao.queryBlListUploadNum(2);
		LOGGER.info("黑名单信息上传成功【{}】条，失败【{}】条", success, failure);
	}

	private void process() {
		blackListInfoDao.resetBlObuType1();
		int i = 1;
		while (true) {
			LOGGER.info("第{}次循环开始", i);
			List<ListRealRecord> records = blackListInfoDao.queryBllistRecordInfos(1, DEFAULT_PROCESS_NUM);
			LOGGER.info("查询{}条数据", records);
			if (CollectionUtils.isEmpty(records)) {
				executor.shutdown();
				LOGGER.info("处理完毕");
				return;
			}
			List<Future<Void>> futures = new ArrayList<>(records.size());
			records.forEach(record -> futures.add(executor.submit(() -> {
				processBListRecord(record);
				return null;
			})));
			baseInfoService.getFutureResult(futures);
			i++;
		}
	}


	private void processBListRecord(ListRealRecord record) {
		String cardId = record.getCardId();
		String obuId = record.getObuId();
		String listId = record.getListID();

		try {
			AbstractSdtsRequest request = null;
			if (StringUtils.isNotBlank(cardId)) {
				request = processCardBlackList(record);
			}

			if (StringUtils.isNotBlank(obuId)) {
				request = processObuBlackList(record);
			}

			if (request == null) {
				LOGGER.info("无法上传黑名单{}", listId);
				return;
			}
			upload(request, listId);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
	}

	 void upload(AbstractSdtsRequest request, String listId) {
		try {
			Class<? extends AbstractSdtsResponse> cls = request instanceof CardBlackListUploadRequest ? CardBlackListUploadResponse.class : OBUBlackListUploadResponse.class;
			AbstractSdtsResponse response = ETCCommHelper.upload(request.getFileName("61"), request, cls);
			LOGGER.info("响应消息：{}，响应时间：{}", response.getInfo(), response.getReceiveTime());
			blackListInfoDao.updateBlObuType1(listId, 1);
		} catch (IOException e) {
			upload(request, listId);
		} catch (Exception e) {
			try {
				recordFailture(request, e, listId);
			} catch (Exception e1) {
				LOGGER.info(e1.getMessage(), e1);
			}
		}
	}

	 void recordFailture(AbstractSdtsRequest request, Exception exp, String listId) {
		String type = request instanceof CardBlackListUploadRequest ? ExecuteTable.CARDBLACKLIST.getStorePath() : ExecuteTable.OBUBLACKLIST.getStorePath();
		if (transferUserInfoDao.queryUploadRspNum(listId, type) > 0) {
			transferUserInfoDao.deleteUploadRsp(listId, type);
		}
		UploadRsp rsp = new UploadRsp();
		rsp.setInfoId(listId);
		rsp.setErrorMessage(exp.getMessage());
		if (exp instanceof ApiRequestException) {
			rsp.setErrorCode(((ApiRequestException) exp).getErrCode());
		}
		try {
			rsp.setRequest(JsonTools.toJsonStr(request));
		} catch (IOException e) {
			LOGGER.error(e.getMessage(), e);
		}
		rsp.setCreateOn(new Date());
		rsp.setType(type);
		transferUserInfoDao.createTestObjcet(rsp);
		//更新上传状态：失败
		blackListInfoDao.updateBlObuType1(listId, 2);
	}

	private AbstractSdtsRequest processCardBlackList(ListRealRecord record) {
		Date optOn = record.getOptOn();
		String creationTime = DateFormatUtils.ISO_DATETIME_FORMAT.format(optOn == null ? record.getStartOn() : optOn);
		Integer type = DEFAULT_OLD_CARD_BLTYPE;
		CardBlackListUploadRequest cb = new CardBlackListUploadRequest();
		cb.setIssuerId(DEFAULT_ISSUERNO);
		cb.setCreationTime(creationTime);
		cb.setType(type);
		cb.setCardId(record.getRoadNetId() + record.getCardId());
		// 进入黑名单
		cb.setStatus(1);
		return cb;
	}

	private AbstractSdtsRequest processObuBlackList(ListRealRecord record) {
		String obuId = record.getObuId();
		Obu obu = blackListInfoDao.queryBsObuById(obuId);
		if (obu == null) {
			LOGGER.info("OBU【{}】信息尚未上传", obuId);
		}
		Date optOn = record.getOptOn();
		String creationTime = DateFormatUtils.ISO_DATETIME_FORMAT.format(optOn == null ? record.getStartOn() : optOn);
		OBUBlackListUploadRequest ob = new OBUBlackListUploadRequest();
		ob.setIssuerId(DEFAULT_ISSUERNO);
		ob.setCreationTime(creationTime);
		//无签挂起
		ob.setType(2);
		ob.setObuId(record.getObuId());
		ob.setStatus(1);
		return ob;
	}

	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		BlackListUploadService service = context.getBean(BlackListUploadService.class);
		service.isRunning=true;
		service.process();
	}

}
